const { db, sqlExec } = require('../db/mysql57');
const minio = require('../db/minio');
const redis = require('../db/redis');

const fileDao = {
    async downloadPublicFile(fileId) {
        let redisResult = await redis.client.get(`file:${fileId}`);
        if (redisResult) {
            return { success: true, url: redisResult };
        }
        let sql = `select browser, uri from PublicImg where id = ?`;
        let data = [ fileId ];
        let result = await sqlExec(sql, data);
        if (result.length === 0) {
            return { success: false, message: '文件不存在' };
        }
        let { browser, uri } = result[0];
        result = await minio.getDownloadUrl(browser, uri, 36000);
        if (result.success) {
            redis.client.set(`file:${fileId}`, result.url);
            redis.client.expire(`file:${fileId}`, 36000 - 10);
        }
        return result;
    }
};

module.exports = fileDao;
